import { createStore } from 'vuex'
import cart from './cart'
import user from './user'

export default createStore({
  state: {
    isLoading: false,
    user: null,
    token: null,
    cart: []
  },
  mutations: {
    setIsLoading (state, flag) {
      state.isLoading = flag
    },
    setUser (state, user) {
      state.user = user
    },
    setToken (state, token) {
      state.token = token
    },
    addGoods2cart (state, cartItem) {
      for (const item of state.cart) {
        if (item.goods.id === cartItem.goods.id) {
          item.num += cartItem.num
          return
        }
      }
      state.cart.push(cartItem)
    },
    delGoodsCart (state, index) {
      state.cart.splice(index, 1)
    },
    delCheckedGoodsCart (state) {
      state.cart.reduceRight( (prev, item, index) => {
        if (item.checked) state.cart.splice(index, 1)
        
        return 0
      }, 0)
    },
    changeGoodsCartChecked (state, { index, flag }) {
      state.cart[index].checked = flag
    },
    loginOut (state) {
      // 清除所有状态信息
      state.user = null
      state.token = null
      state.cart = []
      localStorage.setItem('user', null)
      localStorage.setItem('token', null)
      localStorage.setItem('cart', '[]')
    }
  },
  modules: {
    // cart,
    // user
  }
})
